const { Serverlet } = require('./serverlet')
const multiparty = require('multiparty')
const fs = require('fs')
const path = require('path')

class uploadForm extends Serverlet {
  constructor (req, res) {
    super(req, res)
  }

  get (req, res) {
    res.end('No get methods')
  }

  post (req, res) {
    var form = new multiparty.Form({ uploadDir: './file' })
    form.parse(req, function (err, fields, files) {
      res.writeHead(200, { 'content-type': 'text/plain' })
      res.end(JSON.stringify({ fields: fields, files: files }))
    })
    form.on('file', function (name, file) {
      var dirname = path.dirname(file.path)
      fs.rename(file.path, path.join(dirname, file.originalFilename), function (err) {
        // console.log("yes", err)
      })
    })
  }
}

module.exports = {
  uploadForm
}
